package com.rwx.myjetpack.lifecycle

/**
 * Created by LH on 2023-05-26.
 * Time: 2023-05-26  15:18
 */
//管理所注册进来的接口 ILifecycle
//保存当前view的状态
class LifecycleProvider {

    private var currentLifeState:LifeState=LifeState.DESTORY

    private val lifecycleListener= arrayListOf<AbsLifecycle>()

    fun addLifeListener(iLifecycle: AbsLifecycle){
        if(!lifecycleListener.contains(iLifecycle)){
            lifecycleListener.add(iLifecycle)
        }

    }

    fun removeLifeListener(iLifecycle: ILifecycle){
        lifecycleListener.remove(iLifecycle)
    }

    fun makeLifeState(state: LifeState){

        currentLifeState=state

        lifecycleListener.forEach {
            it.onViewLifeStateChange(state)
        }

        when(state){
            LifeState.CREATE->{
                dispatchCreateState()
            }
            LifeState.START->{
                dispatchStartState()
            }
            LifeState.RESUME->{
                dispatchResumeState()
            }
            LifeState.PAUSE->{
                dispatchPauseState()
            }
            LifeState.STOP->{
                dispatchStopState()
            }
            LifeState.DESTORY->{
                dispatchDestoryState()
            }
        }

    }


    private fun dispatchCreateState() {
        lifecycleListener.forEach {
            it.onCreate()
        }
    }

    private fun dispatchStartState() {

        lifecycleListener.forEach {
            it.onStart()
        }
    }

    private fun dispatchResumeState() {
        lifecycleListener.forEach {
            it.onResume()
        }

    }

    private fun dispatchPauseState() {
        lifecycleListener.forEach {
            it.onPause()
        }

    }

    private fun dispatchStopState() {
        lifecycleListener.forEach {
            it.onStope()
        }


    }

    private fun dispatchDestoryState() {

        lifecycleListener.forEach {
            it.onDestory()
        }
        lifecycleListener.clear()
    }

    fun isAtleast(state: LifeState):Boolean {
        println("current state $currentLifeState === $state")
        val isAtlestState:Boolean=currentLifeState>state
        println("isAtlestState==$isAtlestState")
        return isAtlestState
    }


}